package me.riverslob.test.esper;

import com.espertech.esper.client.*;

import java.util.Random;
import java.util.Date;


/**
 * <br/>Created on 13-9-9 上午11:24
 * @author 郑治明（zm.zheng@zhuche.com）
 * @since 3.1.11
 */
public class ExampleMain {

    public static class Tick {
        String symbol;
        Double price;
        Date timeStamp;

        public Tick(String s, double p, long t) {
            symbol = s;
            price = p;
            timeStamp = new Date(t);
        }
        public double getPrice() {return price;}
        public String getSymbol() {return symbol;}
        public Date getTimeStamp() {return timeStamp;}

        @Override
        public String toString() {
            return "Price: " + price.toString() + " time: " + timeStamp.toString();
        }
    }

    private static Random generator = new Random();

    public static void GenerateRandomTick(EPRuntime cepRT) {

        double price = (double) generator.nextInt(10);
        long timeStamp = System.currentTimeMillis();
        String symbol = "AAPL";
        Tick tick = new Tick(symbol, price, timeStamp);
        System.out.println("Sending tick:" + tick);
        cepRT.sendEvent(tick);
//        cepRT.route(tick);

    }

    public static class CEPListener implements UpdateListener {

        public void update(EventBean[] newData, EventBean[] oldData) {
            System.out.println("Event received: " + newData[0].getUnderlying());
        }

        public void update(Tick newDate) {
            System.out.println(newDate);
        }
    }

    public static void main(String[] args) {

//The Configuration is meant only as an initialization-time object.
        Configuration cepConfig = new Configuration();
        cepConfig.addEventType("StockTick", Tick.class.getName());
        EPServiceProvider cep = EPServiceProviderManager.getProvider("myCEPEngine", cepConfig);

        EPAdministrator cepAdm = cep.getEPAdministrator();
//        EPStatement cepStatement = cepAdm.createEPL("select * from StockTick(symbol='AAPL').win:length(2) having avg(price) > 6.0");
        EPStatement cepStatement = cepAdm.createEPL("select sum(price) from StockTick.win:keepall()");

        cepStatement.addListener(new CEPListener());
//        cepStatement.setSubscriber(new CEPListener());

        EPRuntime cepRT = cep.getEPRuntime();
        // We generate a few ticks...
        for (int i = 0; i < 5; i++) {
            GenerateRandomTick(cepRT);
        }
    }
}
